package com.atguigu.chapter11;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/12 9:30
 */
public class Flink24_UDTAF {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.parseLong(line[1]), Integer.parseInt(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );


        // TODO - UDTF
        // 1.创建 表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // 2.将 流 转换成 Table
        tableEnv.createTemporaryView("sensor", sensorDS, $("id"), $("ts"), $("vc"), $("et").rowtime());
        Table sensor = tableEnv.from("sensor");


        tableEnv.createTemporarySystemFunction("top2",MyTop2.class);

        // TableAPI的方式
        sensor
                .groupBy($("id"))
                .flatAggregate(call("top2",$("vc")).as("top","vc"))
                .select($("id"),$("top"),$("vc"))
                .execute()
                .print();


        env.execute();
    }

    public static class MyTop2 extends TableAggregateFunction<Tuple2<String, Integer>, VcTop2> {


        @Override
        public VcTop2 createAccumulator() {
            return new VcTop2(Integer.MIN_VALUE, Integer.MIN_VALUE);
        }

        public void accumulate(VcTop2 acc, Integer vc) {
            if (vc > acc.getVcTopOne()) {
                // 把原来的Top1，赋值给 Top2，先退位
                acc.setVcTopTwo(acc.getVcTopOne());
                // 把信赖的 vc ，赋值给 Top1，新老大上位
                acc.setVcTopOne(vc);
            } else if (vc > acc.getVcTopTwo()) {
                // 新来的老二 取代 Top2的位置
                acc.setVcTopTwo(vc);
            }
        }


        public void emitValue(VcTop2 acc, Collector<Tuple2<String, Integer>> out) {
            out.collect(Tuple2.of("Top1", acc.getVcTopOne()));
            if (acc.getVcTopTwo() > Integer.MIN_VALUE) {
                out.collect(Tuple2.of("Top2", acc.getVcTopTwo()));
            }
        }

    }
}

/**
 */
